package com.zx.ticket.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;


public class DESUtils {
	private static Key key;
	private static String KEY_STR = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMhCQp0fK6viAZAzYtRFD8sLUbECGL7MSjKEPxYR92aryOZJt1+2w5oQ8jTLs4lGKEdy6qUAZkismfLWppi528UCAwEAAQ==";

	static {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("RC2");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(KEY_STR.getBytes());
			generator.init(secureRandom);
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 对字符串进行加密，返回BASE64的加密字符串 <功能详细描述>
	 * 
	 * @param str
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public static String getEncryptString(String str) {
//		Base64Encoder base64Encoder = new BASE64Encoder();
		Base64 base64Encoder = new Base64();
		//System.out.println(key);
		try {
			byte[] strBytes = str.getBytes("UTF-8");
			Cipher cipher = Cipher.getInstance("RC2");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			return new String(base64Encoder.encode(encryptStrBytes));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	/**
	 * 对BASE64加密字符串进行解密 <功能详细描述>
	 * 
	 * @param str
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public static String getDecryptString(String str) {
		Base64 base64Encoder = new Base64();
		try {
			byte[] strBytes = base64Encoder.decode(str);
			Cipher cipher = Cipher.getInstance("RC2");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			System.out.println("=======================:"+str);
			System.out.println("=======================:"+new String(encryptStrBytes, "UTF-8"));
			return new String(encryptStrBytes, "UTF-8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	public static void main(String[] args) {
//		String name = "bamp";
//		String password = "a123456";
//		String encryname = getEncryptString(name);
//		String encrypassword = getEncryptString(password);
//		
//		System.out.println(encryname);
//		System.out.println(encrypassword);
//
//		System.out.println(getDecryptString(encryname));
//		System.out.println(getDecryptString(encrypassword));
		
	}
}
